<?php
namespace Api\Controller;

use Api\Model\OrderModel;

use Com\Message;

header("content-type:text/html;charset=utf-8");
class MyshopController extends ApiController
{

    public function update_order_shopid()
    {
        $M_pro = M('order_product');
        $list = $M_pro->select();
        foreach ($list as $key) {
            $tem_shop_id = get_table_field($key['product_id'], 'id', 'shop_id', 'product');
            $M_pro->where(array(
                'id' => $key['id']
            ))->setfield('shop_id', $tem_shop_id);
        }
    }

    /**
     * 开店协议
     */
    public function shopProtocol()
    {
        echo C('SHOPPROTOCOL');
    }

    /**
     * 开店
     * 
     * @param
     *            string title
     * @param
     *            string description
     * @param
     *            int headpic
     * @param
     *            int signpic
     */
    public function createShop()
    {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $uid = API_UID;
        $amount = M('member')->where('uid='.$uid)->getField('amount');
        get_table_field(API_UID, 'uid', 'id', 'shop') && response(- 1, '', '不能重复开店');
        $bond = M('bond')->find();
        if ($amount<$bond['money']) {
            response(-3, '', '余额不足');
        }
        M('member')->where('uid='.$uid)->setDec('amount', $bond['money']);
        /* 添加资金流水记录 modify by liujb 20170208 start */
        addCapitalflow('开店保证金',"-".$bond['money'],$uid);
        /* 添加资金流水记录 modify by liujb 20170208 end */
        params_exist(array(
            'title',
            'description',
            'headpic',
            'signpic'
        ));
        
        $data = params_post(array(
            'title',
            'description',
            'headpic',
            'signpic'
        ));
        empty($data['title']) && response(- 1, '', '店铺名称不能为空');
        
        // ! preg_match("/^.{0,60}$/", $data['title']) && response(- 1, '', ' 店铺名称60字以内');
        // ! preg_match("/^.{0,500}$/", $data['description']) && response(- 1, '', ' 店铺简价500字以内');
        ! preg_match("/^[1-9]\d*$/", $data['headpic']) && response(- 1, '', ' 店铺logo参数值错误');
        ! preg_match("/^[1-9]\d*$/", $data['signpic']) && response(- 1, '', ' 店铺形象图参数值错误');
        $data['create_time'] = NOW_TIME;
        $data['update_time'] = NOW_TIME;
        $data['uid'] = API_UID;
        $data['apply_uid'] = API_UID;
        $data['status'] = 1;
        $data['review'] = 0;

        $M_shop = M('shop');
        
        $M_shop->add($data) ? response(1) : response(9);
    }

    /**
     * 店铺信息
     */
    public function myshopInfo()
    {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);

        $M_shop = M('shop');
        
        $shop = $M_shop->where(array(
            'uid' => API_UID
        ))->find();
        empty($shop) && response(- 2, '', '您没有开店');
        $shop['review'] == 0 && response(- 1, '', '您的店铺还未通过审核，请联系管理员');
        $shop['review'] == 2 && response(- 3, '', '您的店铺没有通过审核，请联系管理员');
        $shop['status'] == 2 && response(- 1, '', '您的店铺已被屏蔽，请联系管理员');
        $shop['headpic_path'] = get_url($shop['headpic']);
        $shop['signpic_path'] = get_url($shop['signpic']);
        // 今日订单
        $M_order = M('order');
        $M_order_product = M('Order_product');
        $M_collect_browse_shop = M('collect_browse_shop');
        
        $begintime = date('Y-m-d', NOW_TIME);
        $endtime = date('Y-m-d', NOW_TIME);
        $begintime = strtotime($begintime . " 00:00:00");
        $endtime = strtotime($endtime . " 23:59:59");
        $map = array();
        $map['create_time'] = array(
            'BETWEEN',
            array(
                $begintime,
                $endtime
            )
        );
        // 当天订单金额
        $amount_map = array();
        $amount_map['shop_id'] = $shop['id'];
        $amount_map['create_time'] = array(
            'BETWEEN',
            array(
                    $begintime,
                    $endtime
            )
        );
        if(empty($M_order_product->where($amount_map)->Sum('price'))){
            $shop['amount']=0;
        }else{
            $amount = $M_order_product->where($amount_map)->Sum('price');
            $shop['amount']=$amount*0.99;
        }
        // 当日订单量
        $order_count_map = array();
        $order_count_map['shop_id'] = $shop['id'];
        $order_count_map['create_time'] = array(
            'BETWEEN',
            array(
                $begintime,
                $endtime
            )
        );
        $or_count_list = $M_order_product->where($order_count_map)
            ->group('order_id')
            ->select();
        $shop['order_count'] = count($or_count_list);
        $shop['order_count'] = count($or_count_list);

        // 当天访问
        $visitor_count_map['shop_id'] = $shop['id'];
        $visitor_count_map['create_time'] = array(
            'BETWEEN',
            array(
                $begintime,
                $endtime
            )
        );
        $shop['visitor_count'] = $M_collect_browse_shop->where($visitor_count_map)->count();
        response(1, $shop);
    }

    /**
     * 修改店铺信息
     * 
     * @param
     *            int shop_id
     * @param
     *            string title
     * @param
     *            string description
     * @param
     *            int headpic
     * @param
     *            int signpic
     */
    public function settingMyshop()
    {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $M_shop = M('shop');
        
        params_exist(array(
            'shop_id',
            'title',
            'description',
            'headpic',
            'signpic'
        ));
        
        $data = params_post(array(
            'shop_id',
            'title',
            'description',
            'headpic',
            'signpic'
        ));
        
        ! $M_shop->where(array(
            'uid' => API_UID,
            'id' => $data['shop_id']
        ))->find() && response(- 2, '', '店铺不存在');
        
        empty($data['title']) && response(- 1, '', '店铺名称不能为空');
        // ! preg_match("/^.{0,60}$/", $data['title']) && response(- 1, '', ' 店铺名称60字以内');
        // ! preg_match("/^.{0,500}$/", $data['description']) && response(- 1, '', ' 店铺简价500字以内');
        $data['update_time'] = NOW_TIME;
        
        $M_shop->where(array(
            'id' => $data['shop_id']
        ))->save($data) !== false ? response(1) : response(9);
    }

    /**
     * 获取我的订单
     * 
     * @param
     *            string token
     * @param
     *            int page
     * @param
     *            int page_size
     * @param
     *            int status
     */
    public function getMyOrders()
    {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $Order = D('order');
        $page = I('post.page', 1);
        $page_size = I('post.page_size', 10);
        $offset = ($page - 1) * $page_size;
        $status = I('post.status');
        
        $prefix = C('DB_PREFIX');
        $l_table = $prefix . ('order_product');
        $m_table = $prefix . ('shop');
        $r_table = $prefix . ('product');
        $f_table = $prefix . ('order');
        $model = D('order_product');
        $model = $model->table($l_table . ' l')
            ->join($r_table . ' r on r.id=l.product_id')
            ->join($f_table . ' f on f.id=l.order_id');
        
        $options['field'] = array(
            'f.*'
        );
        
        $options['order'] = 'f.id DESC';
        $options['group'] = 'f.id';
        $filters['r.uid'] = API_UID;

        switch ($status) {

            case '7':
                //--已申请退款
                $filters['f.pay_status'] = OrderModel::ORDER_APPLY_REFUND;
                break;
            case '8':
                //--已退款
                $filters['f.pay_status'] = OrderModel::ORDER_REFUND;
                break;
            case '0':
                //--未支付订单
                $filters['f.pay_status'] = OrderModel::ORDER_UNPAY;
                break;
            case '1':
                //--待发货
                $filters['f.order_status'] = OrderModel::ORDER_CONFIRMED;
                $filters['f.shipping_status'] = array('in', array(OrderModel::SHIPPING_UNSHIPPED, OrderModel::SHIPPING_PARTIALSHIPMENT));
                $filters['f.pay_status'] = OrderModel::ORDER_PAY;
                break;
            case '2':
                //--待收货
                $filters['f.order_status'] = OrderModel::ORDER_CONFIRMED;
                $filters['f.shipping_status'] = OrderModel::SHIPPING_SHIPPED;
                $filters['f.pay_status'] = OrderModel::ORDER_PAY;
                break;
            case '3':
                //--订单完成
                $filters['f.order_status'] = OrderModel::ORDER_COMPLATED;
                $filters['f.shipping_status'] = OrderModel::SHIPPING_SHIPPED;
                $filters['f.review_status'] = OrderModel::REVIEW_UNREVIEWED;
                $filters['f.pay_status'] = OrderModel::ORDER_PAY;
                break;
            case '4':
                //--待评论
                $filters['f.order_status'] = OrderModel::ORDER_COMPLATED;
                $filters['f.shipping_status'] = OrderModel::SHIPPING_SHIPPED;
                $filters['f.review_status'] = OrderModel::REVIEW_REVIEWED;
                $filters['f.pay_status'] = OrderModel::ORDER_PAY;
                break;
            case '5':
                //--取消订单
                $filters['f.order_status'] = OrderModel::ORDER_CANNELED;
                break;
            case '6':
                //--已提交
                $filters['f.order_status'] = array('in', array(OrderModel::ORDER_COMPLATED, OrderModel::ORDER_CONFIRMED));
                break;
        }
        $OPT = new \ReflectionProperty($model, 'options');
        $OPT->setAccessible(true);
        $options['where'] = $filters;
        
        $options = array_merge((array) $OPT->getValue($model), $options);
        
        $total = $model->where($options['where'])->count();
        $model->setProperty('options', $options);
        
        $order_list = $model->limit($offset, $page_size)->select();
        foreach ($order_list as &$item) {
            $item['status_text'] = $Order->getOrderStatusText($item); 
            $order_products = M('order_product')->where(array('order_id'=>$item['id']))->select();
            foreach ($order_products as &$order_product) {
                $product_info = M('product')->where(array('id'=>$order_product['product_id']))->find();
                $order_product['image_path'] = get_url(get_table_field($product_info['id'], 'product_id', 'cover_id', 'product_image'));
                if ($product_info['type'] == 'xianzhi') {
                    $order_product['shop_title'] = '卖家' . get_username($product_info['uid']);
                } else {
                    $shop_info = M('shop')->where(array('id'=>$product_info['shop_id']))->find();
                    $order_product['shop_title'] = $shop_info['title'];
                }
            }
            $item['products'] = $order_products;
        }
        
        $result = array();
        $result['result'] = $order_list;
        $result['total'] = $total;
        $order_list !== false ? response(1, $result) : response(-2);
    }

    /**
     * 订单详情
     * 
     * @param int $order_id            
     *
     */
    public function orderDetail()
    {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        params_exist(array(
            'order_id'
        ));
        
        $order_id = I('post.order_id');
        
        $M_order_product = M('order_product');
        $M_order = M("order");
        $M_product_return = M('product_return');
        /* 增加附加属性值：image、discount */
        $M_product_image = M('product_image');
        
        $M_payment_log = M('payment_log');
        $M_order_shipping = M('order_shipping');
        
        $prefix = C('DB_PREFIX');
        $l_table = $prefix . ('product');
        $m_table = $prefix . ('shop');
        $r_table = $prefix . ('order_product');
        
        $model = D('product');
        $model = $model->table($l_table . ' l')->join($r_table . ' r on r.product_id=l.id');
        
        $options['field'] = array(
            'l.title product_title',
            'l.security_7days',
            'l.security_delivery',
            'l.shop_id',
            'r.product_id',
            'r.price',
            'r.unit_price',
            'r.quantity',
            'r.identify_price',
            'r.product_attr',
            'r.is_comment',
            'r.return_status'
        );
        $OPT = new \ReflectionProperty($model, 'options');
        $OPT->setAccessible(true);
        $join_map = array();
        
        $order_info = $M_order->field('id order_id, uid, order_no,status,create_time,price total_price,province_id,city_id,area_id,consignee,address,mobile')->find($order_id);
        $shop_id = get_table_field($order_id, 'order_id', 'shop_id', 'order_product');
        
        if ($shop_id) {
            $shop_info = M('shop')->find($shop_id);
            $order_info['shop_title'] = $shop_info['title'];
        } else {
            $order_info['shop_title'] = '卖家：' . get_username(API_UID);
        }
        
        $order_info['address_full'] = get_table_field($order_info['province_id'], 'province_id', 'province', 'hat_province') . get_table_field($order_info['city_id'], 'city_id', 'city', 'hat_city') . get_table_field($order_info['area_id'], 'area_id', 'area', 'hat_area') . $order_info['address'];
        
        $status = getStatus('seller_order');
        $order_info['short_status_text'] = getStatus('short_order')[$order_info['status']];
        
        $order_info['sell_status_text'] = getStatus('seller_order')[$order_info['status']];
        
        if ((int) $order_info['status'] >= 1) {
            $tem_payment = $M_payment_log->where(array(
                'order_id' => $order_id
            ))->find();
            $order_info['pay_time'] = $tem_payment['create_time'];
            $order_info['transaction_no'] = $tem_payment['transaction_no'];
        }
        
        if ((int) $order_info['status'] >= 2) {
            $tem_order_shipping = $M_order_shipping->where(array(
                'order_id' => $order_id,
                'type' => 'seller'
            ))->find();
            $order_info['shipping_time'] = $tem_order_shipping['create_time'];
        }
        
        $join_map['r.order_id'] = $order_id;
        $options['where'] = $join_map;
        
        $options = array_merge((array) $OPT->getValue($model), $options);
        $model->setProperty('options', $options);
        
        $Product_list = $model->select();
        
        foreach ($Product_list as &$pro_item) {
            $pro_item['image'] = get_url(get_table_field($pro_item['product_id'], 'product_id', 'cover_id', 'product_image'));
            if ((int) $pro_item['return_status'] > 0) {
                $tem_returns = $M_product_return->where(array(
                    'order_id' => $order_id,
                    'product_id' => $pro_item['product_id']
                ))->find();
                
                if ($tem_returns) {
                    $pro_item['return_time'] = $tem_returns['create_time'];
                    $pro_item['return_money'] = $tem_returns['money'];
                    $pro_item['return_explain'] = $tem_returns['explain'];
                    $pro_item['return_status'] = getStatus('return_status')[$tem_returns['status']];
                    
                    if ($tem_returns['cover_ids']) {
                        $pro_item['return_images'] = array();
                        
                        $cover_id_array = explode(',', $tem_returns['cover_ids']);
                        foreach ($cover_id_array as $key => $value) {
                            $pro_item['return_images'][] = get_url($value);
                        }
                    }
                }
            }
        }
        $order_info['products'] = $Product_list;
        $order_info ? response(1, $order_info) : response(- 2);
    }

    /**
     * 退款操作
     * 
     * @param int $order_id            
     * @param int $product_id            
     * @param
     *            int status 2 同意退款 4拒绝退款
     */
    public function refundOperation()
    {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        params_exist(array(
            'order_id',
            'product_id',
            'status'
        ));
        
        $order_id = I('post.order_id');
        $product_id = I('post.product_id');
        $status = I('post.status');
        
        $M_order = M('order');
        $M_product = M('product');
        $M_order_product = M('order_product');
        $M_product_return = M('product_return');
        
        $order_info = $M_order->where(array(
            'id' => $order_id,
            'uid' => API_UID
        ));
        empty($order_info) && response(- 2, '', '订单不存在');
        
        $order_product_map = array(
            'order_id' => $order_id,
            'product_id' => $product_id
        );
        $product_order = $M_order_product->where($order_product_map)->find();
        
        empty($product_order) && response(- 2, '', '不存在的订单商品');
        
        ! preg_match('/^2|4$/', $status) && response(- 1, '', 'status值错误');
        
        $up_result = $M_order_product->where($order_product_map)->setfield('return_status', $status);
        $M_product_return->where($order_product_map)->setfield('status', $status);
        $up_result !== false ? response(1) : response(- 9);
    }

    /**
     * 发货
     * 
     * @param
     *            int order_id
     * @param
     *            int shipping_code
     * @param
     *            string code
     * @param
     *            int cover_id[]
     */
    public function shipments()
    {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        params_exist(array(
            'order_id',
            'shipping_code',
            'code'
        ));
        $cover_id = I('post.cover_id');
        is_array($cover_id) && $cover_id = implode(',', $cover_id);
        
        $data = params_post(array(
            'order_id',
            'shipping_code',
            'code'
        ));
        ! get_table_field($data['order_id'], 'id', 'id', 'order') && response(- 2, '', '订单不存在');
        
        $data['type'] = 'seller';
        $data['create_time'] = NOW_TIME;
        $data['cover_ids'] = $cover_id;
        
        $M_order = M('order');
        $M_order_shipping = M('order_shipping');
        
        $M_order->where(array(
            'id' => $data['order_id']
        ))->setField('status', 2);
        $orderinfo = $M_order->find($data['order_id']);
        if ($M_order_shipping->where(array(
            'order_id' => $data['order_id']
        ))->find()) {
            
            $result = $M_order_shipping->where(array(
                'order_id' => $data['order_id']
            ))->save($data);
            empty($result) && response(- 9);
        } else {
            $data['order_id'] = $data['order_id'];
            $result = $M_order_shipping->add($data);
            empty($result) && response(- 9);
        }
        addMessage(1, '发货通知', '您的订单' . $orderinfo['order_no'] . '已发货,快递公司是' . $data['shipping_code'] . ',快递单号是' . $data['code'], $orderinfo['uid']);
        response(1);
    }

    /**
     * 收到的评论
     * 
     * @param
     *            string token
     * @param
     *            int page
     * @param
     *            int page_size
     * @param
     *            int status
     */
    public function receiveComment()
    {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        
        $page = I('post.page', 1);
        $page_size = I('post.page_size', 10);
        $offset = ($page - 1) * $page_size;
        $status = I('status');
        
        $M_order_product = M('order_product');
        $M_order = M("order");
        $M_product_comment = M('product_comment');
        $M_picture = M('picture');
        $M_product_comment_message = M('product_comment_message');
        
        $prefix = C('DB_PREFIX');
        $l_table = $prefix . ('product_comment');
        $m_table = $prefix . ('product');
        $r_table = $prefix . ('product_comment_message');
        
        $options = array();
        $join_map = array();
        $join_map['m.uid'] = API_UID;
        
        $model = M('product_comment');
        $model = $model->table($l_table . ' l')->join($m_table . ' m ON m.id=l.product_id');
        $options['field'] = array(
            'l.id',
            'l.create_time',
            'l.rate',
            'l.uid buyer_id',
            'l.content',
            'l.cover_ids',
            'l.rating_desc',
            'l.rating_attitude',
            'l.rating_speed',
            'l.rating_shipping',
            'm.id product_id',
            'm.uid'
        );
        
        $options['order'] = 'l.id DESC';
        
        $OPT = new \ReflectionProperty($model, 'options');
        $OPT->setAccessible(true);
        $options['where'] = $join_map;
        
        $options = array_merge((array) $OPT->getValue($model), $options);
        $total = $model->where($options['where'])->count();
        // 总数
        $model->setProperty('options', $options);
        
        $list = $model->select();
        int_to_string($list, array(
            'rate' => getStatus('rate_text')
        ));
        foreach ($list as &$item) {
            $my_re = $M_product_comment_message->where(array(
                'uid' => API_UID,
                'comment_id' => $item['id'],
                'is_saler' => 1
            ))
                ->field('content,create_time')
                ->select();
            $item['my_recomment'] = $my_re ? $my_re : '';
            
            $item['format_time'] = time_format($item['create_time']);
            if ($item['cover_ids']) {
                $tem_image = $M_picture->where(array(
                    'id' => array(
                        'in',
                        $item['cover_ids']
                    )
                ))
                    ->field('id,create_time,')
                    ->select();
                foreach ($tem_image as $imageitem) {
                    $item['images'][] = get_url($imageitem['id']);
                }
            }
        }
        $result = array();
        $result['total'] = $total;
        $result['result'] = $list;
        $list ? response(1, $result) : response(- 2);
    }

    /**
     * 回复评论
     * 
     * @param
     *            int comment_id
     * @param
     *            content
     */
    function replyComment()
    {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $M_product_comment_message = M('product_comment_message');
        $comment_id = I('comment_id');
        params_exist(array(
            'comment_id',
            'content'
        ));
        $data = params_post(array(
            'comment_id',
            'content'
        ));
        $data['create_time'] = NOW_TIME;
        $data['is_saler'] = 1;
        $data['uid'] = API_UID;
        
        ! preg_match('/.{2,60}+$/', $data['content']) && response(- 1, '', '回复内容在2-60个字符之间');
        
        $M_product_comment_message->add($data) ? response(1) : response(- 9);
    }

}